<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    =={{msg}}
    <hr />
    <ul>
      <li v-for="(item, index) in list" :key="item.id">

        <input type="checkbox" v-model="item.chk">
        ==={{item.name}}==={{item.price}}===
        <button @click="sub(item.id)">-</button>
        <input type="text" v-model.number="item.num">
        <button @click="add(item.id)">+</button>
      </li>
    </ul>
    <input type="checkbox" v-model="flagAll"> 总价:{{total}}
  </div>
  <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.7.14/vue.min.js"></script>
  <script>
    var vm = new Vue({
      el: "#app",
      data: {
        msg: 'hello  vue',
        chkAll: false,
        list: [
          { id: 1, name: '李宁', price: 10, num: 1, chk: false },
          { id: 2, name: '安踏', price: 20, num: 2, chk: true },
          { id: 3, name: '特步', price: 30, num: 3, chk: false },
          { id: 4, name: '耐克', price: 40, num: 4, chk: false },
          { id: 5, name: '阿迪', price: 50, num: 5, chk: false }
        ]
      },

      methods: {
        sub(id) {
          const obj = this.list.find(item => item.id == id)
          // console.log(obj);
          if (obj.num <= 1) {
            return alert('已经是最小数量了')
          } else {
            obj.num -= 1
          }

        },
        add(id) {
          const obj = this.list.find(item => item.id == id)
          // console.log(obj);
          obj.num += 1
        }
      },
      computed: {
        total() {
          var newArr = this.list.filter(item => item.chk)
          return newArr.reduce((sum, item) => sum + item.num * item.price, 0)
        },
        //全选
        flagAll: {
          get() {
            //第一次全选框值为false
            return this.chkAll
          },
          set(val) {
            //拿到当前复选框的值,因为修改了,所以全选框值为true
            console.log(val);
            //循环数组,让所有小复选框值为全选框的值
            this.list.forEach(item => {
              item.chk = val
            })
          }
        }
      },
      watch: {
        // chkAll (newVal) {
        //   console.log(1111);
        //   // if (newVal) {
        //   this.list.forEach(item => {
        //     item.chk = newVal
        //   })
        //   // }
        // },
        // list (newVal) {
        //   console.log(this.list.every(item => item.chk), 9999);
        //   this.chkAll = this.list.every(item => item.chk)
        // }
        list: {
          handler(newVal) {
            // console.log(this.list.every(item => item.chk), 9999);
            this.chkAll = this.list.every(item => item.chk)
          },
          deep: true,
          immediate: true
        }
      },
    })

  </script>
</body>

</html>